<template>
  <div>
    <template v-if="formConf.popupType==='general'">
      <el-dialog :title="!dataForm.id ? '新建' : '编辑'" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body
        :visible.sync="visible" class="JNPF-dialog JNPF-dialog_center" lock-scroll
        :width="formConf.generalWidth">
        <parser :form-conf="formConf" @submit="submitForm" :relationInfo="relationInfo" :key="key" ref="dynamicForm"
          v-if="!loading" />
        <span slot="footer" class="dialog-footer">
          <template v-if="formConf.hasPrintBtn && formConf.printId && dataForm.id && false">
            <el-button type="primary" @click="print">
              {{formConf.printButtonText||'打 印'}}
            </el-button>
          </template>
          <el-button @click="visible = false">{{formConf.cancelButtonText||'取 消'}}</el-button>
          <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading">
            {{formConf.confirmButtonText||'确 定'}}</el-button>
        </span>
      </el-dialog>
    </template>
    <template v-if="formConf.popupType==='fullScreen'">
      <transition name="el-zoom-in-center">
        <div class="JNPF-preview-main">
          <div class="JNPF-common-page-header">
            <el-page-header @back="goBack" :content="!dataForm.id ? '新建' : '编辑'" />
            <div class="options">
              <template v-if="formConf.hasPrintBtn && formConf.printId && dataForm.id && false">
                <el-button type="primary" @click="print">
                  {{formConf.printButtonText||'打 印'}}
                </el-button>
              </template>
              <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading">
                {{formConf.confirmButtonText||'确 定'}}</el-button>
              <el-button @click="goBack">{{formConf.cancelButtonText||'取 消'}}</el-button>
            </div>
          </div>
          <div class="dynamic-form-main" :style="{margin: '0 auto',width:formConf.fullScreenWidth}">
            <parser :form-conf="formConf" @submit="submitForm" :relationInfo="relationInfo" :key="key" ref="dynamicForm"
              v-if="!loading" />
          </div>
        </div>
      </transition>
    </template>
    <template v-if="formConf.popupType==='drawer'">
      <el-drawer :title="!dataForm.id ? '新建' : '编辑'" :visible.sync="visible"
        :wrapperClosable="false" :size='formConf.drawerWidth' append-to-body
        class="JNPF-common-drawer">
        <div class="JNPF-flex-main">
          <div class="dynamicForm">
            <parser :form-conf="formConf" @submit="submitForm" :relationInfo="relationInfo" :key="key" ref="dynamicForm"
              v-if="!loading" />
          </div>
          <div class="drawer-footer">
            <template v-if="formConf.hasPrintBtn && formConf.printId && dataForm.id && false">
              <el-button type="primary" @click="print">
                {{formConf.printButtonText||'打 印'}}
              </el-button>
            </template>
            <el-button @click="visible = false">{{formConf.cancelButtonText||'取 消'}}</el-button>
            <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading">
              {{formConf.confirmButtonText||'确 定'}}</el-button>
          </div>
        </div>
      </el-drawer>
    </template>
    <print-browse :visible.sync="printBrowseVisible" :id="formConf.printId" :formId="dataForm.id" />
    <DiagnosisBox v-if="diagnosisBoxVisible" ref="DiagnosisBox"  @refreshDataList="refresh"/>
  </div>
</template>

<script>
import { createModel, updateModel, getModelInfo } from '@/api/onlineDev/visualDev'
import Parser from '@/components/Generator/parser/Parser'
import PrintBrowse from '@/components/PrintBrowse'
import DiagnosisBox from './DiagnosisBox'
import { deepClone } from '@/utils'
export default {
  components: { Parser, PrintBrowse,DiagnosisBox },
  props: {
    relationInfo: {
      type: Object,
      default: () => { }
    }
  },
  data() {
    return {
      visible: false,
      diagnosisBoxVisible:false,
      key: +new Date(),
      formConf: {},
      dataForm: {
        id: '',
        data: ''
      },
      modelId: '',
      formData: {},
      btnLoading: false,
      loading: true,
      isPreview: false,
      useFormPermission: false,
      printBrowseVisible: false,
      formOperates: [],
      existSubTableList:false,
      listTables:[],
      clientUUID:'' ,// by jdeng 用于在client生成id，主要场景是为子表在创建状态也能操作
      subFieldMap:{},// by jdeng 子表与主表的字段映射扁平化
    }
  },
  beforeDestroy() {
    if(!this.relationInfo){ // 将主表数据缓存在全局变量中，用于子表对应字段做自动填充
      this.$store.commit('generator/SET_MAINTABLE_DYNAMIC_MODEL_EXTRA', {})
      this.$store.commit('generator/SET_MAINTABLE_OBJ', {})
    }
  },
  methods: {

    goBack() {
      this.$emit('refreshDataList')
    },
    print() {
      if (this.isPreview) return this.$message({ message: '功能预览不支持打印', type: 'warning' })
      this.printBrowseVisible = true
    },
    /**
     * 个性化：执行故障诊断
     */
    doDiagnosis(){
      this.diagnosisBoxVisible = true
        this.$nextTick(() => {
          this.$refs.DiagnosisBox.init(this.dataForm.id)
        })
    },
    refresh(isRefresh) {
      this.diagnosisBoxVisible = false

      if (isRefresh) 
        this.init(this.formConf
      , this.modelId
      , this.dataForm.id
      , this.isPreview
      , this.useFormPermission)
    },

    init(formConf, modelId, id, isPreview, useFormPermission) {
      // debugger
      /**
       * by jdeng
       */
      this.$store.commit('generator/SET_VIEW_STATUS', 'edit')

      this.formConf = deepClone(formConf)
      this.modelId = modelId
      this.isPreview = isPreview
      this.useFormPermission = useFormPermission
      this.dataForm.id = id || ''
      this.getFormOperates()
      this.loading = true
      /**
       * by jdeng
       * 
       */
      this.formatSubFieldMap()
      // end
      this.$nextTick(() => {
        if (this.dataForm.id) {
          let extra = {
            modelId,
            id,
            type: 2,
            isNew:false
          }
          this.$store.commit('generator/SET_DYNAMIC_MODEL_EXTRA', extra)
          getModelInfo(modelId, this.dataForm.id).then(res => {
            this.dataForm = res.data
            if (!this.dataForm.data) return
            this.formData = JSON.parse(this.dataForm.data)
            /**
             * by jdeng
             */
            if(!this.relationInfo){ // 将主表数据缓存在全局变量中，用于子表对应字段做自动填充
              this.$store.commit('generator/SET_MAINTABLE_DYNAMIC_MODEL_EXTRA', this.formatMainFormData(this.formConf,this.formData))
              this.$store.commit('generator/SET_MAINTABLE_OBJ', this)
            }

            this.fillFormData(this.formConf, this.formData)
            this.$nextTick(() => {
              this.visible = true
              this.loading = false
            })
            
          })
          this.clientUUID = ''
        } else {
          // this.$store.commit('generator/SET_DYNAMIC_MODEL_EXTRA', {})
          this.clientUUID = this.hlsz.guid()
          this.formData = {}
          this.fillFormData(this.formConf, this.formData)
          this.visible = true
          this.loading = false
          let extra = {
            modelId,
            id:this.clientUUID,
            type: 2,
            isNew:true
          }
          this.$store.commit('generator/SET_DYNAMIC_MODEL_EXTRA', extra)
          
          if(!this.relationInfo){ // 将主表数据缓存在全局变量中，用于子表对应字段做自动填充
              this.$store.commit('generator/SET_MAINTABLE_DYNAMIC_MODEL_EXTRA', {})
              this.$store.commit('generator/SET_MAINTABLE_OBJ', this)
            }
        }
        this.key = +new Date()
      })
    },
    getFormOperates() {
      if (this.isPreview || !this.useFormPermission) return
      const permissionList = this.$store.getters.permissionList
      const modelId = this.$route.meta.modelId
      const list = permissionList.filter(o => o.modelId === modelId)
      this.formOperates = list[0] && list[0].form ? list[0].form : []
    },
    /**
     * by jdeng 子表与主表的字段映射扁平化
     */
    formatSubFieldMap(){
      // debugger
      if(this.relationInfo&&this.relationInfo.fieldMap){
        let map = {}
        this.relationInfo.fieldMap.forEach((o)=>{
          if(o.tableField&&o.relationField){
            map[o.tableField] = o.relationField
          }
        })
        this.subFieldMap = map
      }
    },
    /**
     * by jdeng
     * 扁平化主表的字段和值的对应关系
     * 用于子表对应字段做自动填充
     * @param {*} data 
     */
    formatMainFormData(form,data){
      let mainData = {}
      const loop = list => {
        for (let i = 0; i < list.length; i++) {
          let item = list[i]
          if (item.__vModel__) {
            const val = data[item.__vModel__]
            if (val !== undefined) {
              mainData[item.__vModel__] = val
            }
          }
          // end by jdeng
          if (item.__config__ && item.__config__.jnpfKey !== 'table' && item.__config__.jnpfKey !== 'listTable' && item.__config__.children && Array.isArray(item.__config__.children)) {
            loop(item.__config__.children)
          }
        }
      }
      loop(form.fields)
      // debugger
      return mainData
    },
    
    resetMainTableAllFieldValue(){
      this.$refs.dynamicForm && this.$refs.dynamicForm.resetMainTableAllFieldValue && this.$refs.dynamicForm.resetMainTableAllFieldValue()
    },


    fillFormData(form, data) {
      // by jdeng
      this.initDynamicConfig(form.fields,data)
      // end by jdeng
      const loop = list => {
        for (let i = 0; i < list.length; i++) {
          let item = list[i]
          if (item.__vModel__) {
            let val = data[item.__vModel__]
            /**
               * by jdeng
               */
               if(this.relationInfo&&this.subFieldMap){
                //  debugger
                 let mainField = this.subFieldMap[item.__vModel__]
                 if(mainField){
                  let mainTableDynamicModelExtra = this.$store.state.generator.mainTableDynamicModelExtra
                  if(mainTableDynamicModelExtra){
                    let mainValue = mainTableDynamicModelExtra[mainField]
                    if(mainValue !== undefined){
                      val = mainValue
                    }
                  }
                 }
               }
            if (val !== undefined && val != null) {
              item.__config__.defaultValue = val
            }
            if (!this.isPreview && this.useFormPermission) {
              let noShow = true
              if (this.formOperates && this.formOperates.length) {
                noShow = !this.formOperates.some(o => o.enCode === item.__vModel__)
              }
              noShow = item.__config__.noShow ? item.__config__.noShow : noShow
              this.$set(item.__config__, 'noShow', noShow)
            }
          }
          /**
           * by jdeng 设置defaultValue
           */
          if (item.__config__ && item.__config__.jnpfKey === 'listTable'){
            this.existSubTableList = true
            // 在src/components/Generator/parser/Parser.vue中会将__config__.defaultValue赋值给foreignId属性
            item.__config__.defaultValue = this.dataForm.id?this.dataForm.id:this.clientUUID
            this.$set(item.__config__, 'viewStatus', 'edit')
            let __subTableDatas__ = data['__subTableDatas__']
            if(__subTableDatas__){
              let subData = __subTableDatas__[item.__config__.tableName]
              this.$set(item.__config__, 'initData', subData)
            }
            this.listTables.push(deepClone(item))

          }
          // end by jdeng
          if (item.__config__ && item.__config__.jnpfKey !== 'table' && item.__config__.jnpfKey !== 'listTable' && item.__config__.children && Array.isArray(item.__config__.children)) {
            loop(item.__config__.children)
          }
        }
      }
      loop(form.fields)
      this.fillForeignId(form.fields,data)
    },
    fillForeignId(componentList,formData){
      // debugger
      if(!this.relationInfo){
        return
      }
      let {foreignField,foreignId} = this.relationInfo
      if(foreignField&&foreignId){
        componentList.forEach(cur => {
          if (cur.__vModel__ === foreignField) {
            cur.__config__.defaultValue = foreignId
            return;
          }
        })
      }
    },
    /**
     * by jdeng 解析动态配置
     * @param {*} componentList 
     */
     initDynamicConfig(componentList,formData){
      // debugger
      let dynamicItem
      componentList.forEach(cur => {
        if (cur.__vModel__ === 'F_FormDynamicConf') {
          dynamicItem = cur
          return;
        }
      })
      if(!dynamicItem){
        return;
      }
      const config = dynamicItem.__config__
      const vModel = dynamicItem.__vModel__
      const initConfigCall = (list,key,prop,value)=>{
        // debugger
        list.forEach(cur => {
          const config = cur.__config__
          if (cur.__vModel__ === key) {
            config[prop]=value
            return
          }
          if (cur.__config__.jnpfKey == 'table') return
          if (config.children) initConfigCall(config.children, key,prop,value)
        })
      }
      try{
        // debugger
          let dynamicJsonStr = formData[vModel]
          if(dynamicJsonStr){
            config.defaultValue = dynamicJsonStr
            let dynamicJson = JSON.parse(dynamicJsonStr)
            if(dynamicJson){
              if(dynamicJson.showOrHide){ // 动态设置显示隐藏属性
                let showOrHide = dynamicJson.showOrHide
                for (let key in showOrHide) {
                  const newVal = !!showOrHide[key]
                  initConfigCall(componentList,key,'noShow',!newVal)
                }
              }
              if(dynamicJson.currency){ // 动态设置显示隐藏属性
                let currency = dynamicJson.currency
                for (let key in currency) {
                  const newVal = currency[key]
                  initConfigCall(componentList,key,'currency',newVal)
                }
              }
              if(dynamicJson.flowStag){ // 动态设置流程步骤属性
                
              }
            }
           
          }
      }catch(e){
        console.error(e)
      }
    },
    submitForm(data, callback) {
      if (!data) return
      this.btnLoading = true
      this.dataForm.data = JSON.stringify(data)
      debugger

      /**
       * by jdeng
       */
      this.dataForm.clientUUID = !this.existSubTableList||this.dataForm.id ?'':this.clientUUID
      // end by jdeng

      this.doAllTableSubmit((subDataForms,callbacks)=>{
        const formMethod = this.dataForm.id ? updateModel : createModel
        if(subDataForms){
          this.dataForm.subDataForms = JSON.stringify(subDataForms)
        }
        formMethod(this.modelId, this.dataForm).then(res => {
          this.$message({
            message: res.msg,
            type: 'success',
            duration: 1500,
            onClose: () => {
              let isclose = true
              let ret = undefined
              if (callback && typeof callback === "function") ret = callback(res.data)
              this.btnLoading = false
              isclose = ret == false ?false:true
              if(isclose){
                this.visible = false
                this.$emit('refreshDataList', true)
              }
              
            }
          })
        }).catch(() => { this.btnLoading = false })
      })

      
    },
    dataFormSubmit() {
      if (this.isPreview) return this.$message({ message: '功能预览不支持数据保存', type: 'warning' })
      debugger
      this.$refs.dynamicForm && this.$refs.dynamicForm.submitForm()
    },
    /**
     * 
     * by jdeng
     */
     doAllTableSubmit(mainCallback){
      debugger
      if(this.$refs.dynamicForm&&this.listTables&&this.listTables.length>0){
        let count = this.listTables.length
        let index = 0
        let callbacks = []
        let subDataForms = {}
        let nextFun = (item,subData,callback)=>{
          debugger
          index++
          if(!item){
            if(index===count){
              mainCallback(subDataForms,callbacks)
            }
            return
          }
          let obj = {}
          if(subData){
            subDataForms[item.__config__.tableName] = subData
          }
          if(callback){
            callbacks.push(callback)
          }
          
          if(index===count){
            mainCallback(subDataForms,callbacks)
          }
        }
        this.listTables.forEach((item,index)=>{
          let ref = 'listTable_'+item.__config__.tableName
          let listTableComp = this.$refs.dynamicForm.$refs[ref]
          if(listTableComp
            &&listTableComp.$refs.listTable){
              let subDynamicForm = listTableComp.$refs.listTable.$refs.dynamicForm
              if(subDynamicForm){
                // debugger
                subDynamicForm.doSubFormSubmit((subData,callback)=>{
                  nextFun(item,subData,callback)
                })
              }else{
                nextFun()
              }
          }
        })
      }else{
        mainCallback()
      }
     
    }
  }
}
</script>